﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Contacts.DA
{
    public class CategoriaContatos : IData<ContactCategory>
    {

        ContactsEntities contactsEntities;

        public void Delete(ContactCategory item)
        {
            if (contactsEntities == null)
                contactsEntities = new ContactsEntities();

            contactsEntities.DeleteObject(item);

            contactsEntities.AcceptAllChanges();
        }

        public void Delete(int Id)
        {
            if (contactsEntities == null)
                contactsEntities = new ContactsEntities();

            object cat;

            EntityKey key = new EntityKey("ContactsEntities.ContactCategory", "Id_ContactCategory", Id);

            if (contactsEntities.TryGetObjectByKey(key ,out cat))
            {
                contactsEntities.DeleteObject(cat);
                contactsEntities.AcceptAllChanges();
            }
        }

        public void Save(ContactCategory item)
        {
            if (contactsEntities == null)
                contactsEntities = new ContactsEntities();

            contactsEntities.ContactCategories.AddObject(item);

            contactsEntities.AcceptAllChanges();
        }

        public ContactCategory Get(int Id)
        {
            if (contactsEntities == null)
                contactsEntities = new ContactsEntities();

            ContactCategory categoria = (from cat in contactsEntities.ContactCategories
                                         where cat.Id_ContactCategory == Id
                                         select cat).FirstOrDefault();

            return categoria;
        }

        public List<ContactCategory> ToList()
        {
            List<ContactCategory> returnList = new List<ContactCategory>();

            if (contactsEntities == null)
                contactsEntities = new ContactsEntities();

            var categoriaContatos = from cat in contactsEntities.ContactCategories
                                    select cat;

            returnList = categoriaContatos.ToList();

            return returnList;
        }
    }
}
